﻿using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Workflow.Application.DTOs.Input;
using Workflow.Application.DTOs.Output;
using Workflow.Application.ErrorCode;
using Workflow.Application.Extend;
using Workflow.Application.IService;
using Workflow.Application.Step;
using Workflow.Domain.Enums;
using Workflow.Domain.Models;
using Workflow.Infrastructure.IRepository;
using WorkflowCore.Interface;
using WorkflowCore.Models;
using WorkflowCore.Models.DefinitionStorage.v1;
using WorkflowCore.Primitives;
using WorkflowCore.Services;
using WorkflowCore.Services.DefinitionStorage;
using Yitter.IdGenerator;

namespace Workflow.Application.Service
{
    public class WorkflowService: IWorkflowService
    {
        #region 依赖注入
        private readonly IBaseRepository<AuditModel> auditBase;
        private readonly IBaseRepository<WorkflowDefinitionModel> definitionBase;
        private readonly IBaseRepository<WorkflowInstanceModel> instanceBase;
        private readonly IBaseRepository<WorkflowGroupModel> groupBase;
        /// <summary>
        /// automapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// token上下文
        /// </summary>
        private readonly IHttpContextAccessor contextAccessor;
        private readonly IWorkflowHost workflowHost;
        /// <summary>
        /// 流程注册
        /// </summary>
        private readonly IWorkflowRegistry workflowRegistry;
        private readonly IDefinitionLoader definitionLoader;
        private readonly ILogger<WorkflowService> logger;
        /// <summary>
        /// 依赖注入
        /// </summary>
        /// <param name="auditBase"></param>
        /// <param name="definitionBase"></param>
        /// <param name="instanceBase"></param>
        /// <param name="groupBase"></param>
        /// <param name="mapper"></param>
        /// <param name="contextAccessor"></param>
        /// <param name="workflowHost"></param>
        /// <param name="workflowRegistry"></param>
        /// <param name="definitionLoader"></param>
        /// <param name="logger"></param>
        public WorkflowService(
            IBaseRepository<AuditModel> auditBase, 
            IBaseRepository<WorkflowDefinitionModel> definitionBase, 
            IBaseRepository<WorkflowInstanceModel> instanceBase,
            IBaseRepository<WorkflowGroupModel> groupBase,
            IMapper mapper, 
            IHttpContextAccessor contextAccessor, 
            IWorkflowHost workflowHost, 
            IWorkflowRegistry workflowRegistry, 
            IDefinitionLoader definitionLoader, 
            ILogger<WorkflowService> logger)
        {
            this.auditBase = auditBase;
            this.definitionBase = definitionBase;
            this.instanceBase = instanceBase;
            this.groupBase = groupBase;
            this.mapper = mapper;
            this.contextAccessor = contextAccessor;
            this.workflowHost = workflowHost;
            this.workflowRegistry = workflowRegistry;
            this.definitionLoader = definitionLoader;
            this.logger = logger;
        }
        #endregion
        /// <summary>
        /// 流程模板添加
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> AddDefinition(WorkflowDefinitionAddInput input)
        {
            try
            {
                var userId = Convert.ToInt64(contextAccessor.HttpContext.User.FindFirstValue("UserId"));
                var definitionmodel = await definitionBase.GetValue(x => x.Title == input.Title);
                //判断重复id
                if (definitionmodel != null)
                {
                    return ApiResult<int>.Fail("已有该模板", 0);
                }
                int num = 1;
                foreach(var i in input.StepNodes)
                {
                    i.StepId = num.ToString();
                    num++;
                    i.NextStepId = num.ToString();
                }
                input.StepNodes.Last().NextStepId=nameof(Workflow.Application.Step.EndStep);
                var definition = mapper.Map<WorkflowDefinitionModel>(input);
                definition.WorkflowDefinitionId=YitIdHelper.NextId().ToString();
                definition.Version = 1;
                definition.Id = YitIdHelper.NextId();
                definition.StepNodes = JsonConvert.SerializeObject(input.StepNodes);
                definition.DataType = JsonConvert.SerializeObject(input.DataType);
                definition.CreatedUserId = userId;
                //流程注册
                LoadDefinition(definition);
                //返回值
                int c = await definitionBase.AddRange(definition);
                if (c <= 0)
                {
                    return ApiResult<int>.Fail("添加流程模板失败", 0);
                }
                else
                {
                    return ApiResult<int>.Success(1, "添加流程模板成功");
                }
            }
            catch (Exception ex)
            {

                return ApiResult<int>.Fail(ex.Message, 0);
            }
        }
        /// <summary>
        /// 流程注册
        /// </summary>
        /// <param name="input">查询参数，包含分页、标题和分组条件</param>
        /// <returns>分页结果</returns>
        /// <param name="model"></param>
        public void LoadDefinition(WorkflowDefinitionModel model)
        {
            try
            {
                // 1.判断是否已经被注册
                if (workflowRegistry.IsRegistered(model.WorkflowDefinitionId, model.Version))
                {
                    return;
                }
                // 2. 创建流程定义对象
                DefinitionSourceV1 source = new()
                {
                    Id = model.WorkflowDefinitionId,
                    Version = model.Version,
                    Description = model.Title,
                    DataType = $"{typeof(Dictionary<string, object>).FullName},{typeof(Dictionary<string, object>).Assembly.FullName}",
                };
                //反序列号
                var steps = JsonConvert.DeserializeObject<List<WorkflowStepNode>>(model.StepNodes);
                // 3. 添加步骤
                //3.1开始
                var start = new StepSourceV1()
                {
                    Id = nameof(StartStep),
                    Name = nameof(StartStep),
                    StepType = $"{typeof(StartStep).FullName},{typeof(StartStep).Assembly.FullName}",
                    NextStepId = steps.First().StepId
                };
                source.Steps.Add(start);
                //3.2过程
                foreach (var i in steps)
                {
                    //多人审批foreeach
                    var foreachstep = new StepSourceV1()
                    {
                        Id = i.StepId,
                        Name = i.StepName,
                        StepType = $"{typeof(ForeachExtend).FullName},{typeof(ForeachExtend).Assembly.FullName}",
                        NextStepId = i.NextStepId
                    };
                    //节点
                    long auditlong = YitIdHelper.NextId();
                    var auditstep = new StepSourceV1()
                    {
                        Id = $"{i.StepId}@{auditlong}",
                        Name = $"{i.StepName}@{auditlong}",
                        StepType = $"{typeof(AuditStep).FullName},{typeof(AuditStep).Assembly.FullName}",
                    };
                    foreachstep.Inputs.TryAdd("Collection", $"\"{JsonConvert.SerializeObject(i.StepNodeDetail.AuditPersons)}\"");
                    BuildWhen(auditstep, i);
                    foreachstep.Do.Add(new() { auditstep });
                    source.Steps.Add(foreachstep);
                }
                //3.3结束
                var end = new StepSourceV1()
                {
                    Id = nameof(Workflow.Application.Step.EndStep),
                    Name = nameof(Workflow.Application.Step.EndStep),
                    StepType = $"{typeof(Workflow.Application.Step.EndStep).FullName},{typeof(Workflow.Application.Step.EndStep).Assembly.FullName}",
                };
                source.Steps.Add(end);
                // 4. 加载流程
                var json = JsonConvert.SerializeObject(source);
                definitionLoader.LoadDefinition(json, Deserializers.Json);
            }
            catch (Exception ex)
            {

                throw;
            }
        }
        /// <summary>
        /// 构造When及其子节点
        /// </summary>
        /// <param name="stepBody"></param>
        /// <param name="input"></param>
        private void BuildWhen(StepSourceV1 stepBody, WorkflowStepNode input)
        {
            try
            {
                //通过
                var agree = new StepSourceV1()
                {
                    Id = $"{input.StepId}@agree",
                    Name = $"{input.StepName}@agree",
                    StepType = $"{typeof(AgreeStep).FullName},{typeof(AgreeStep).Assembly.FullName}",
                };
                var whenAgree = new StepSourceV1()
                {
                    Id = $"{input.StepId}@whenAgree",
                    Name = $"{input.StepName}@whenAgree",
                    StepType = $"{typeof(When).FullName},{typeof(When).Assembly.FullName}",
                };
                whenAgree.Inputs.TryAdd("ExpectedOutcome", $"\"{WorkFlowAuditStatuEnum.Pass}\"");
                whenAgree.Do.Add(new() { agree });
                stepBody.Do.Add(new() { whenAgree });
                //驳回
                var reject = new StepSourceV1()
                {
                    Id = $"{input.StepId}@reject",
                    Name = $"{input.StepName}@reject",
                    StepType = $"{typeof(RejectStep).FullName},{typeof(RejectStep).Assembly.FullName}",
                };
                var whenReject = new StepSourceV1()
                {
                    Id = $"{input.StepId}@whenReject",
                    Name = $"{input.StepName}@whenReject",
                    StepType = $"{typeof(When).FullName},{typeof(When).Assembly.FullName}",
                };
                whenAgree.Inputs.TryAdd("ExpectedOutcome", $"\"{WorkFlowAuditStatuEnum.UnApprove}\"");
                whenReject.Do.Add(new() { reject });
                stepBody.Do.Add(new() { whenReject });
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 流程发起
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> StartWorkflow(WorkflowStartInput input)
        {
            try
            {
                var definition = await definitionBase.GetValue(x => x.Id == input.DefinitionId);
                if (definition == null)
                {
                    return ApiResult<int>.Fail("出现异常，请刷新页面", 1);
                }
                var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(JsonConvert.SerializeObject(input));
                var workflowId = await workflowHost.StartWorkflow(definition.WorkflowDefinitionId, definition.Version, data);
                var userId = Convert.ToInt64(contextAccessor.HttpContext.User.FindFirstValue("UserId"));
                var userName = contextAccessor.HttpContext.User.FindFirstValue("UserName");
                WorkflowInstanceModel model = new WorkflowInstanceModel()
                {
                    Id=YitIdHelper.NextId(),
                    CreatedUserId = userId,
                    WorkflowInstanceId = workflowId,
                    Title = definition.Title,
                    FormFields = JsonConvert.SerializeObject(input.FormData),
                    ApplicantUserId = userId,
                    ApplicantUserName = userName,
                    StatuEnum = WorkflowInstanceStatuEnum.WorkflowStart
                };
                //返回值
                int c = await instanceBase.AddRange(model);
                if (c <= 0)
                {
                    return ApiResult<int>.Fail("流程发起失败", 0);
                }
                else
                {
                    return ApiResult<int>.Success(1, "流程发起成功");
                }
            }
            catch (Exception ex)
            {

                return ApiResult<int>.Fail(ex.Message, 0);
            }
        }
        /// <summary>
        /// 审批
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Audit(AuditInput input)
        {
            try
            {
                var userId = Convert.ToInt64(contextAccessor.HttpContext.User.FindFirstValue("UserId"));
                AuditModel model = await auditBase.GetValue(x => x.Id == input.AuditId);
                if (model == null)
                {
                    return ApiResult<int>.Fail("出现异常，请刷新页面", 0);
                }
                // 发送审批事件
                await workflowHost.PublishEvent(input.AuditId.ToString(), model.WorkflowId, input);
                model.StatuEnum = input.OperateTypeEnum;
                model.Remark = input.Remark;
                model.UpdatedTime = DateTime.Now;
                //返回值
                int c = await auditBase.UpdateRange(model);
                if (c <= 0)
                {
                    return ApiResult<int>.Fail("操作失败", 0);
                }
                else
                {
                    return ApiResult<int>.Success(1, "操作成功");
                }
                
            }
            catch (Exception ex)
            {

                return ApiResult<int>.Fail(ex.Message, 0);
            }
        }

    

        /// <summary>
        /// 获取流程模板列表
        /// </summary>
        /// <param name="input">查询参数，包含分页、标题和分组条件</param>
        /// <returns>流程模板列表</returns>
        public async Task<List<WorkflowDefinitionDto>> GetDefinitions(GetWorkflowInput input)
        {
            try
            {
                List<WorkflowDefinitionDto> dtos = new List<WorkflowDefinitionDto>();
                List<WorkflowGroupModel> groupModels = groupBase.GetAll().ToList();
                List<WorkflowDefinitionModel> models = definitionBase.GetAll().ToList();
                if (input.GroupId != null)
                {
                    groupModels = groupModels.Where(x => x.Id == input.GroupId).ToList();
                }
                if (input.Title != null)
                {
                    models = models.Where(x => x.Title.Contains(input.Title)).ToList();
                }
                foreach (var i in groupModels)
                {
                    WorkflowDefinitionDto dto = new WorkflowDefinitionDto()
                    {
                        GroupId = i.Id,
                        GroupName = i.GroupName,
                    };
                    dto.list = mapper.Map<List<WorkflowDefinitionList>>(models.Where(x => x.GroupId == i.Id).ToList());
                    dtos.Add(dto);
                }
                return dtos;
            }
            catch (Exception)
            {

                return null;
            }
        }



        /// <summary>
        /// 获取我的待办任务
        /// </summary>
        /// <param name="input">查询参数，包含分页、流程标题、模板组、申请人和创建时间范围</param>
        /// <returns>待办任务列表</returns>
        public async Task<ApiPaging<MyTaskDto>> GetMyTasks(GetMyTasksInput input)
        {
            try
            {
                // 从token中获取当前用户ID
                var currentUserId = GetCurrentUserId();
                if (currentUserId <= 0)
                {
                    return new ApiPaging<MyTaskDto>
                    {
                        Code = StateCodeEnum.Fail,
                        Message = "获取当前用户信息失败",
                        TotalCount = 0,
                        Items = new List<MyTaskDto>()
                    };
                }

                // 使用左连接查询当前用户的待办任务及其关联的流程实例
                var query = auditBase.GetAll()
                    .Where(x => x.AuditUserId == currentUserId && x.StatuEnum == WorkFlowAuditStatuEnum.UnAudited)
                    .Join(
                        instanceBase.GetAll(),
                        audit => audit.WorkflowId,
                        instance => instance.WorkflowInstanceId,
                        (audit, instance) => new { Audit = audit, Instance = instance }
                    );

                // 根据流程标题筛选
                if (!string.IsNullOrWhiteSpace(input.Title))
                {
                    query = query.Where(x => x.Instance.Title.Contains(input.Title));
                }

                // 根据申请人筛选
                if (input.ApplicantId.HasValue && input.ApplicantId.Value > 0)
                {
                    query = query.Where(x => x.Instance.ApplicantUserId == input.ApplicantId.Value);
                }

                // 根据创建时间范围筛选
                if (input.StartDate.HasValue)
                {
                    query = query.Where(x => x.Instance.CreatedTime >= input.StartDate.Value);
                }
                if (input.EndDate.HasValue)
                {
                    // 将结束日期调整为当天的23:59:59，以包含整个结束日期
                    var endDate = input.EndDate.Value.Date.AddDays(1).AddSeconds(-1);
                    query = query.Where(x => x.Instance.CreatedTime <= endDate);
                }

                // 根据模板组筛选（如果提供了模板组ID）
                if (input.GroupId.HasValue && input.GroupId.Value > 0)
                {
                    // 获取指定组的流程定义ID列表
                    var definitionIds = await definitionBase.GetAll()
                        .Where(x => x.GroupId == input.GroupId.Value)
                        .Select(x => x.WorkflowDefinitionId)
                        .ToListAsync();

                    // 先将数据加载到内存中
                    var queryList = await query.ToListAsync();

                    // 在内存中筛选符合模板组条件的数据
                    queryList = queryList
                        .Where(x => x.Instance.WorkflowInstanceId != null &&
                                x.Instance.WorkflowInstanceId.Contains(':') &&
                                definitionIds.Contains(x.Instance.WorkflowInstanceId.Split(':')[0]))
                        .ToList();

                    // 重新构建查询
                    query = queryList.AsQueryable();
                }

                // 排序
                query = query.OrderByDescending(x => x.Audit.CreatedTime);

                // 计算总数
                var totalCount = query.Count();

                // 分页查询
                var items = query.Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).ToList();

                // 转换为DTO
                var dtoList = items.Select(item => {
                    var dto = new MyTaskDto
                    {
                        Id = item.Audit.Id,
                        WorkflowId = item.Audit.WorkflowId,
                        StepName = item.Audit.StepName,
                        Status = item.Audit.StatuEnum,
                        StatusDescription = GetStatusDescription(item.Audit.StatuEnum),
                        CreatedTime = item.Audit.CreatedTime,
                        // 直接从连接结果中获取流程实例信息
                        Title = item.Instance.Title,
                        ApplicantId = item.Instance.ApplicantUserId,
                        ApplicantName = item.Instance.ApplicantUserName
                    };

                    return dto;
                }).ToList();

                // 返回分页结果
                return new ApiPaging<MyTaskDto>
                {
                    Code = StateCodeEnum.Ok,
                    Message = "获取成功",
                    TotalCount = totalCount,
                    Items = dtoList
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取我的待办任务列表失败");
                return new ApiPaging<MyTaskDto>
                {
                    Code = StateCodeEnum.Fail,
                    Message = "获取我的待办任务列表失败: " + ex.Message,
                    TotalCount = 0,
                    Items = new List<MyTaskDto>()
                };
            }
        }

        /// <summary>
        /// 获取流程业务实例列表
        /// </summary>
        /// <param name="input">查询参数，包含分页、流程标题、申请人和创建时间范围</param>
        /// <returns>流程业务实例列表</returns>
        public async Task<ApiPaging<WorkflowInstanceDto>> GetWorkflowInstances(GetWorkflowInstanceInput input)
        {
            try
            {
                // 获取当前用户ID
                var currentUserId = GetCurrentUserId();
                if (currentUserId <= 0)
                {
                    return new ApiPaging<WorkflowInstanceDto>
                    {
                        Code = StateCodeEnum.Fail,
                        Message = "获取当前用户信息失败",
                        TotalCount = 0,
                        Items = new List<WorkflowInstanceDto>()
                    };
                }

                // 获取所有流程业务实例并应用筛选条件
                var query = instanceBase.GetAll();

                // 默认只能查看自己发起的流程实例
                query = query.Where(x => x.ApplicantUserId == currentUserId);

                // 如果提供了申请人ID参数，并且不是当前用户，则需要检查权限
                // 这里假设管理员或特定角色可以查看所有流程实例，需要根据实际权限逻辑调整
                if (input.ApplicantUserId.HasValue && input.ApplicantUserId.Value > 0 && input.ApplicantUserId.Value != currentUserId)
                {
                    // 检查当前用户是否有权限查看其他用户的流程实例
                    bool hasPermission = CheckUserPermission(currentUserId, "ViewAllWorkflowInstances");
                    if (!hasPermission)
                    {
                        return new ApiPaging<WorkflowInstanceDto>
                        {
                            Code = StateCodeEnum.Fail,
                            Message = "您没有权限查看其他用户的流程实例",
                            TotalCount = 0,
                            Items = new List<WorkflowInstanceDto>()
                        };
                    }
                    
                    // 有权限，按指定的申请人ID筛选
                    query = query.Where(x => x.ApplicantUserId == input.ApplicantUserId.Value);
                }

                // 根据标题筛选（如果提供了标题）
                if (!string.IsNullOrWhiteSpace(input.Title))
                {
                    query = query.Where(x => x.Title.Contains(input.Title));
                }

                // 根据创建时间范围筛选
                if (input.StartDate.HasValue)
                {
                    query = query.Where(x => x.CreatedTime >= input.StartDate.Value);
                }
                if (input.EndDate.HasValue)
                {
                    // 将结束日期调整为当天的23:59:59，以包含整个结束日期
                    var endDate = input.EndDate.Value.Date.AddDays(1).AddSeconds(-1);
                    query = query.Where(x => x.CreatedTime <= endDate);
                }

                // 排序
                query = query.OrderByDescending(x => x.CreatedTime);

                // 计算总数
                var totalCount = await query.CountAsync();

                // 分页查询
                var items = await query.Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).ToListAsync();

                // 转换为DTO
                var dtoList = items.Select(item => {
                    var dto = mapper.Map<WorkflowInstanceDto>(item);

                    // 设置状态描述
                    dto.StatusDescription = GetInstanceStatusDescription(item.StatuEnum);

                    return dto;
                }).ToList();

                // 返回分页结果
                return new ApiPaging<WorkflowInstanceDto>
                {
                    Code = StateCodeEnum.Ok,
                    Message = "获取成功",
                    TotalCount = totalCount,
                    Items = dtoList
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取流程业务实例列表失败");
                return new ApiPaging<WorkflowInstanceDto>
                {
                    Code = StateCodeEnum.Fail,
                    Message = "获取流程业务实例列表失败: " + ex.Message,
                    TotalCount = 0,
                    Items = new List<WorkflowInstanceDto>()
                };
            }
        }

        /// <summary>
        /// 获取流程实例状态描述
        /// </summary>
        /// <param name="status">流程实例状态枚举</param>
        /// <returns>状态描述</returns>
        private string GetInstanceStatusDescription(WorkflowInstanceStatuEnum status)
        {
            return status switch
            {
                WorkflowInstanceStatuEnum.WorkflowStart => "发起",
                WorkflowInstanceStatuEnum.Processing => "处理中",
                WorkflowInstanceStatuEnum.Completed => "已完成",
                WorkflowInstanceStatuEnum.Abandoned => "已废弃",
                WorkflowInstanceStatuEnum.Reject => "驳回",
                _ => "未知状态"
            };
        }

        /// <summary>
        /// 获取流程详情
        /// </summary>
        /// <param name="input">查询参数，包含流程实例ID</param>
        /// <returns>流程详情，包括基本信息、表单数据和审批记录</returns>
        public async Task<ApiResult<WorkflowDetailDto>> GetWorkflowDetail(GetWorkflowDetailInput input)
        {
            try
            {
                if (string.IsNullOrEmpty(input.WorkflowInstanceId))
                {
                    return new ApiResult<WorkflowDetailDto>
                    {
                        Code = StateCodeEnum.Fail,
                        Message = "流程实例ID不能为空",
                        Data = null
                    };
                }

                // 获取当前用户ID
                var currentUserId = GetCurrentUserId();
                if (currentUserId <= 0)
                {
                    return new ApiResult<WorkflowDetailDto>
                    {
                        Code = StateCodeEnum.Fail,
                        Message = "获取当前用户信息失败",
                        Data = null
                    };
                }

                // 获取流程实例基本信息
                var instance = await instanceBase.GetAll()
                    .FirstOrDefaultAsync(x => x.WorkflowInstanceId == input.WorkflowInstanceId);

                if (instance == null)
                {
                    return new ApiResult<WorkflowDetailDto>
                    {
                        Code = StateCodeEnum.Fail,
                        Message = "未找到指定的流程实例",
                        Data = null
                    };
                }

                // 检查权限：只能查看自己发起的流程或者有权限查看的流程
                if (instance.ApplicantUserId != currentUserId)
                {
                    // 检查是否是审批人
                    bool isAuditor = await auditBase.GetAll()
                        .AnyAsync(x => x.WorkflowId == input.WorkflowInstanceId && x.AuditUserId == currentUserId);
                    
                    // 检查是否有查看所有流程的权限
                    bool hasPermission = CheckUserPermission(currentUserId, "ViewAllWorkflowInstances");
                    
                    if (!isAuditor && !hasPermission)
                    {
                        return new ApiResult<WorkflowDetailDto>
                        {
                            Code = StateCodeEnum.Fail,
                            Message = "您没有权限查看此流程详情",
                            Data = null
                        };
                    }
                }

                // 获取审批历史记录
                var auditHistory = await auditBase.GetAll()
                    .Where(x => x.WorkflowId == input.WorkflowInstanceId)
                    .OrderBy(x => x.CreatedTime)
                    .ToListAsync();

                // 转换为DTO
                var instanceDto = mapper.Map<WorkflowInstanceDto>(instance);
                instanceDto.StatusDescription = GetInstanceStatusDescription(instance.StatuEnum);

                var auditDtos = auditHistory.Select(item => {
                    var dto = mapper.Map<AuditDto>(item);
                    dto.StatusDescription = GetStatusDescription(item.StatuEnum);
                    return dto;
                }).ToList();

                // 构建结果
                var result = new WorkflowDetailDto
                {
                    BasicInfo = instanceDto,
                    FormData = instance.FormFields, // 使用FormFields字段存储表单数据
                    AuditHistory = auditDtos
                };

                return new ApiResult<WorkflowDetailDto>
                {
                    Code = StateCodeEnum.Ok,
                    Message = "获取成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取流程详情失败");
                return new ApiResult<WorkflowDetailDto>
                {
                    Code = StateCodeEnum.Fail,
                    Message = "获取流程详情失败: " + ex.Message,
                    Data = null
                };
            }
        }

        /// <summary>
        /// 获取当前用户ID
        /// </summary>
        /// <returns>当前用户ID</returns>
        private long GetCurrentUserId()
        {
            try
            {
                // 从HttpContext中获取当前用户ID
                // 注意：这里的实现取决于你的认证系统，可能需要根据实际情况调整
                var userIdClaim = contextAccessor.HttpContext?.User?.Claims?.FirstOrDefault(c => c.Type == "UserId");
                if (userIdClaim != null && long.TryParse(userIdClaim.Value, out long userId))
                {
                    return userId;
                }
                return 0;
            }
            catch
            {
                return 0;
            }
        }

        /// <summary>
        /// 获取审批状态描述
        /// </summary>
        /// <param name="status">审批状态枚举</param>
        /// <returns>状态描述</returns>
        private string GetStatusDescription(WorkFlowAuditStatuEnum status)
        {
            return status switch
            {
                WorkFlowAuditStatuEnum.UnAudited => "待审核",
                WorkFlowAuditStatuEnum.Pass => "通过",
                WorkFlowAuditStatuEnum.UnApprove => "驳回",
                WorkFlowAuditStatuEnum.RejectToHistory => "驳回至历史",
                WorkFlowAuditStatuEnum.TransferOffice => "转办",
                WorkFlowAuditStatuEnum.Discard => "废弃",
                WorkFlowAuditStatuEnum.StartQuery => "打回上一级",
                _ => "未知状态"
            };
        }

        /// <summary>
        /// 检查用户权限
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="permissionCode">权限代码</param>
        /// <returns>是否有权限</returns>
        private bool CheckUserPermission(long userId, string permissionCode)
        {
            // TODO: 实现实际的权限检查逻辑
            // 这里只是一个示例，需要根据实际的权限系统进行实现
            // 可以从数据库中查询用户角色和权限，或者调用权限服务
            
            // 示例：假设用户ID为1的是管理员，有所有权限
            if (userId == 1)
            {
                return true;
            }
            
            // 默认没有权限
            return false;
        }
    }
}
